package drds.server.sqlparser;

import java.util.List;

import drds.server.sqlparser.parser.ExpressionParser;
import drds.server.sqlparser.parser.Mark;
import drds.server.sqlparser.parser.ParserException;
import drds.server.sqlparser.parser.ParserUtils;
import drds.server.sqlparser.parser.StatementParser;
import drds.server.sqlparser.sqlobject.SqlObject;
import drds.server.sqlparser.sqlobject.expression.Expression;
import drds.server.sqlparser.sqlobject.statement.Statement;
import drds.server.sqlparser.visitor.OutputVisitor;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class SQLUtils {

	public static String toSQLString(SqlObject sqlObject) {
		StringBuilder sb = new StringBuilder();
		OutputVisitor visitor = createOutputVisitor(sb);

		sqlObject.accept(visitor);

		String sql = sb.toString();
		return sql;
	}

	public static Expression toSQLExpr(String sql) {
		ExpressionParser expressionParser = ParserUtils.createExpressionParser(sql);
		Expression expression = expressionParser.parseExpression();

		if (expressionParser.getLexer().getMark() != Mark.EOF) {
			throw new ParserException("illegal sql expr : " + sql);
		}

		return expression;
	}

	public static String format(String sql) {
		return format(sql, null);
	}

	public static String format(String sql, List<Object> parameterList) {
		try {
			StatementParser statementParser = ParserUtils.createStatementParser(sql);

			Statement statementList = statementParser.parseStatement();

			// return toSQLString(statementList, parameterList);
		} catch (ParserException ex) {
			return sql;
		}
		return sql;
	}

	public static OutputVisitor createOutputVisitor(Appendable out) {
		return createOutputVisitor(out, null);
	}

	public static OutputVisitor createOutputVisitor(Appendable out, //
			List<Statement> statementList) {

		return new OutputVisitor(out);

	}

	public static Statement parseStatementList(String sql) {
		StatementParser statementParser = ParserUtils.createStatementParser(sql);
		Statement statementList = statementParser.parseStatement();
		if (statementParser.getLexer().getMark() != Mark.EOF) {
			throw new RuntimeException("syntax error : " + sql);
		}
		return statementList;
	}

}
